<template>
  <div>
    <el-dialog
      draggable
      :close-on-click-modal="false"
      v-model="dialogVisible"
      :title="formData.id ? '编辑文章分类' : '添加文章分类'"
      width="30%">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cate_name">
          <el-input v-model="formData.cate_name" />
        </el-form-item>
        <el-form-item label="分类别名" prop="cate_alias">
          <el-input v-model="formData.cate_alias" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
// import { ref } from 'vue';
import { addCateApi, editCateApi } from '@/api/article.js';
const emit = defineEmits(['refresh']);
const dialogVisible = ref(false);
const formRef = ref();
const formData = ref({
  cate_name: '',
  cate_alias: ''
});
const formRules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,15}$/,
      message: '请输入1-15位的非空字符',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '请输入1-15位的字母或数字',
      trigger: 'blur'
    }
  ]
};
const open = (row) => {
  dialogVisible.value = true;
  formData.value = { ...row };
  formRef.value.resetFields();
  console.log(formData);
};
const addSubmit = () => {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const isEdit = formData.value.id;
      if (isEdit) {
        const res = await editCateApi(formData.value);
        if (res.code == 0) {
          ElMessage.success(res.message);
        } else {
          ElMessage.error(res.message);
        }
      } else {
        const res = await addCateApi(formData.value);
        if (res.code == 0) {
          ElMessage.success(res.message);
        } else {
          ElMessage.error(res.message);
        }
      }
      dialogVisible.value = false;
      formRef.value.resetFields();
      emit('refresh');
    }
  });
};
defineExpose({ open });
</script>
<style lang="less">
// dialog标题下加一条线
.el-dialog__header {
  width: 100%;
  border-bottom: 1px solid #409eff;
}

// dialog标题黑色
.el-dialog__title {
  font-weight: 600;
  color: #409eff;
}
</style>
